const app = getApp();
var http = require('../../service/http.js'); //请求类
var util = require('../../utils/util.js'); //工具类
// 引入SDK核心类
var QQMapWX = require('../../utils/qqMap/qqmap-wx-jssdk.min.js');

// 实例化API核心类
var demo = new QQMapWX({
  key: '2UBBZ-N45WV-RHTPK-UOUWB-SVK7E-XMBCA' // 必填
});
var adTime = ''; //用于清除计时事件
Page({
  data: {
    //---当前页名称--------------
    pageName: 'home',
    isShowAD: 'notYet', //是否展示首页的投放广告
    isBindPhone: false, //是否绑定了手机号
    adDetailArr: [], //广告信息
    adInterval: '', //每张广告投放时间间隔
    countAdTime: '', //广告计时时间
    closeAdAnimationData: '', //广告隐藏动画
    showPage: false, //是否展示页面
    cityName: '', //程序内默认city
    cityArray: [], //全部城市

    AreaIcon: true, //地区选择图标（true--未展开）
    //-----登录--------------------------
    codeExpiryTime: 300000, //code过期时间
    isAuthorization: 'notYet', //是否授权登陆
    userInfoScope: false, //用户授权状态
    animationData: '', //用户登陆动画
    isLogin: false, //是否点击了登录按钮
    showLogin: 'notYet', //是否展示登录
    isshow: false, //是否显示mask
    toBuy: false, //是否是立即购买

    //首页广告跳转
    adProId: '', //广告携带商品id
    carouseImgArr: [],
    defalutImgArr: [
      'https://momjoin.com/order/carouselImgs/1529372998590.jpg',
      'https://momjoin.com//order/carouselImgs/1529373009387.jpg',
      'https://momjoin.com/order/carouselImgs/1529373018996.jpg'
    ], //默认广告图片
    autoplay: true, //开启自动切换
    interval: 4000, //自动切换时间间隔
    duration: 500, //滑动时长
    showLoadding: true, //加载动画gif
    showLine1: false, //首页更多精彩横排展示几个商品false --两个 true 1个
    imgHeight: '', //商品图片高度
    currentSwiper: 0, //当前播放图片序号

    //---商品相关---------------------------------------------------
    products: [], //所有商品
    hotPorducts: [], //热销商品
    productId: '', //当前商品id
    pageNo: 1, //商品列表分页
    total: 0, //商品分页总数
    pageSize: '', //分页查询商品数量
    product: {}, //商品
    minPrice: 0, //最小价格（初始化商品价格范围）
    maxPrice: 0, //最大价格
    skuTitles: [], //sku中title
    isActive: false, //是否被选中
    skus: [], //所有sku内容
    distAttrs: [], //商品sku属性及属性值信息
    chooseAttrids: [], //已选属性id
    //----------暂存购物车商品信息-------------------
    itemId: '', //暂存购物车商品id 
    skuId: '', //skuid
    count: 1, //购物车数量
    stock: 0, //默认库存
    //addCart:false,//初始化购物车动画
    //----------分享 绘图----------------------------
    showCanvas: false, //是否展示绘图

    //-----------跳转地址---------------------------
    pageUrl: '', //跳转地址
    //----------商品分享分享人inviter-店铺id------------------------------
    inviter: '', //分享人inviter(通过二维码扫描进入小程序获取)
    shopuid: '', //店铺id
    shopName: '', //店铺名称
    isOwnShop: '', //是否是自己有分销店铺
    inShareShop: false, //是否在分享店铺
    shareKey: '', //shareKey =='0'为分享标识

    //sku所有价格---
    skuPrices: [],

    //测试
    noticeScrollTop: 1, // 通知滚动条滚动高度
    isBottom: false, //是否触底
    paySendTemp: '', //是否从发送的模板消息进入，待付款

    //用户地理位置 经纬度
    // userLongitude: '', //用户经度
    // userLatitude: '', //用户纬度
    //商户所在经纬度
    shopLongitude: 116.428396, //商户经度
    shopLatitude: 39.824966, //商户纬度
    distance: '', //和商户之间的距离显示

    //---登录后有无优惠券---
    hasShopCoupon: '',
    // swiper指示点位置
    pinUser: 1,
    pinParms: '', //拼团携带数据
    // 查看营业执照
    showBusiness: false, //是否展示营业执照按钮

    // 显示引导'添加到我的小程序'
    showCollectionTip:'',
    showGuideMask: false,// 引导添加‘我的小程序’蒙层
  },
  onLoad: function(option) {

    wx.hideTabBar();
    //加载首页及计时广告成功回调（控制广告及页面展示顺序）
    var loadAdTask = setInterval(() => {

      let isShowAD = app.data.isShowAD;

      if (isShowAD === false || isShowAD === true) {
        console.log('adDetailArr', app.data.adDetailArr);
        clearInterval(loadAdTask); //结束周期任务
        if (isShowAD) {

          this.setData({
            adDetailArr: app.data.adDetailArr, //播放广告内容
            adInterval: app.data.adInterval, //时长间隔
            countAdTime: app.data.countAdTime, //计时时间
            isShowAD: app.data.isShowAD, //是否展示广告
          
          })
          //广告计时
          this.countAdTime();

        } else { //没有广告且已经登录，初始化广告数据 

          this.setData({
            adDetailArr: [], //播放广告内容
            adInterval: '', //时长间隔
            countAdTime: '', //计时时间
            isShowAD: false, //是否展示广告
          })

        }
        // 展示页面、检查是否需要登录
        setTimeout(() => {
          this.setData({
            showPage: true
          })
        }, 200)
      }

    }, 100);

    console.log("进入homejs-onLoad：本地店铺信息", wx.getStorageSync('shopInfo'))

    console.log("homejs页onload分享参数", option);

    let shopInfo = wx.getStorageSync('shopInfo') || {}; //店铺信息、是否有绑定或自己的店铺

    let isAuthorization = app.data.isAuthorization;
    //--------------------------分享店铺参数------------------------------------
    //本地店铺信息、店铺id、店铺名称、分享标识、
    let [shopuid, isOwnShop, shareKey, inviter, pinUser, pinParms, paySendTemp] = [shopInfo.shopuid || '', shopInfo.isOwnShop || '', '', '', '', '', ''];

    //分享参数信息
    if (option.parms) { //转发进入
      //店铺id 、店铺名称 、分享标识
      let paramArray = option.parms.split('/');
      [shopuid, inviter, shareKey] = paramArray;
    } else if (option.scene) { //分享二维码海报进入
      console.log(option.scene);
      let scene = decodeURIComponent(option.scene); //商品id 分享人uid 转发标识
      let param = scene.split('/');
      [shopuid, inviter, shareKey] = param;
    } else if (option.pinParms) {
      pinUser = 1;
      pinParms = option.pinParms;
      let pinArray = option.pinParms.split('/');
      inviter = pinArray[1];
      shopuid = pinArray[2];
      shareKey = pinArray[3];
    } else if (option.paySendTemp) {
      paySendTemp = option.paySendTemp || ''; //是否是通过模板消息进入查看订单列表

      if (paySendTemp == '1' || paySendTemp == 1) { //是否是消息模板进入(查看订单)
        wx.navigateTo({
          url: '/pages/user/pages/orders/orders?checkOrders=1',
        })
      }

    }

    //设置分享店铺信息
    this.setData({
      scrollViewHeight: app.data.scrollViewHeight, //滚动窗口高度
      shopuid: shopuid,
      shareKey: shareKey,
      inviter: inviter,
      paySendTemp: paySendTemp || '', //是否从模板消息进入跳转到全部订单
      pinUser: pinUser,
      pinParms: pinParms,
    })

    //参与拼单用户
    if (pinUser == 1) {
      this.toJoinPinPage(pinParms); //到商品详情页
      return;
    }


    // app.checkShopCoupon(shareKey); //查看有误店铺优惠券
    console.log("shopuid:" + shopuid + "inviter：" + inviter + "shareKey:" + shareKey);
  },
  /**
   * 跳转参加拼团页
   */
  toJoinPinPage: function(pinParms) {
    console.log('toJoinPinPage参团', pinParms);
    wx.navigateTo({
      url: '/pages/product/product?pinParms=' + pinParms,
    });
  },
  onShow: function() {

    if (this.data.pinUser != 1 && this.data.paySendTemp != 1) { //等于1为拼团分享直接跳转不需要执行本页面逻辑代码

      let [shopuid, inviter, shareKey] = [this.data.shopuid, this.data.inviter, this.data.shareKey]
      if (shareKey == '0' || shareKey == '1') { //分享标识,取消店铺过期标识
        app.recoverShopInfoTime(); //分享过期标识 false
      } else if (app.data.shopInfoTimeOut === true || shareKey == '') { //非分享且已经过期，清除店铺信息
        shopuid = '';
        inviter = '';
      }
      console.log('app.data.cityArray', app.data.cityArray);
      this.setData({
        shopuid: shopuid,
        inviter: inviter,
        cityArray: app.data.cityArray,
        cityName: app.data.cityName,
        showCollectionTip: app.data.showCollectionTip//添加到我的小程序
      })

      app.checkSession(shopuid, inviter, shareKey);

      this.checkSessionTask();

      //刷新banner轮播
      if (this.data.carouseImgArr.length == 0) {
        this.getCarouseImgArr();
      }

      //改变商品图片父级高度
      this.changeImgHeight();
    }

  },
  //检查登录态
  checkSessionTask: function() {
    let checkSessionTask = setInterval(() => {
      let isAuthorization = app.data.isAuthorization;

      if (isAuthorization === true || isAuthorization === false) {

        //返回店铺信息
        clearInterval(checkSessionTask); //结束任务

        if (isAuthorization) { //已登录
          this.showProductList();
          if (this.data.showLogin === true) {
            this.cancelAnimation();
          }

        } else { //未登录
          let showLogin = this.data.showLogin
          if (showLogin !== true) { //未展示登录
            this.loginAnimation();
            return;
          }
        }
      }

    }, 100)
  },
  // 检查登录
  userLoginTask: function() {

    let userLoginTask = setInterval(() => {
      let isAuthorization = app.data.isAuthorization;
      if (isAuthorization === true) {

        clearInterval(userLoginTask);
        this.showProductList();
        if (this.data.showLogin === true) {
          this.cancelAnimation();
        }
      }
    }, 100)
    setTimeout(() => {
      let isAuthorization = app.data.isAuthorization;
      if (isAuthorization === false) {
        util.showToast('连接失败，请重试', 1000, 'none', function(res) {
          this.loginAnimation();
        })
      }
    }, 10000)
  },
  /**
   *检查何时展示优惠券（获取地理位置后） 
   */
  showCouponTask: function() {

    let showCouponTask = setInterval(() => {
      let cityName = wx.getStorageSync('cityName');
      console.log('cityName-', cityName);
      let hasShopCoupon = app.data.hasShopCoupon;
      if (cityName !== '') { //（获取地理位置后） 
        clearInterval(showCouponTask);
        wx.hideTabBar();
        this.setData({
          isshow: true
        })
      }
    }, 500)

  },
  /**
   * 展示商品列表、底部菜单、获取地理位置
   */
  showProductList: function() {

    let showProductListTask = setInterval(() => {

      let hasGotShopInfo = app.data.hasGotShopInfo;
      let isShowAD = this.data.isShowAD;

      if ((hasGotShopInfo === true || hasGotShopInfo === false) && isShowAD === false) {

        clearInterval(showProductListTask);
        this.checkShopCouponTask(); //展示底部菜单
        if (!wx.getStorageSync('cityName')) { //没有地理位置
          this.getLocation(); //获取page变量cityName
        }
        let products = this.data.products;
        if (products.length < 1) {
          this.loadListByCityNameTask(); //根据城市加载商品列表
        }

        app.setShopTitle(); //设置店铺标题

        this.setData({
          isAuthorization: app.data.isAuthorization,
          showLogin: false,
          isBindPhone: wx.getStorageSync('isBindPhone'), //根据绑定状态获取用户授权
          showCollectionTip: app.data.showCollectionTip,// 显示引导'添加到我的小程序'
        })
      }

    }, 100)

  },

  //-------登陆动画-------------------
  loginAnimation: function() {

    app.loginAnimation(); //this 用于传递 userlogin 的分享店铺信息
    this.setData({
      isLogin: false,
      isAuthorization: app.data.isAuthorization,
      animationData: app.data.animationData,
      showLogin: app.data.showLogin,
    })

  },

  onShareAppMessage: function(options) {

    let shopInfo = wx.getStorageSync('shopInfo') || '';
    let shopName = shopInfo.shopName ? shopInfo.shopName : ''; //转发携带店铺名称
    let shopuid = shopInfo.shopuid ? shopInfo.shopuid : ''; //店铺id

    let inviter = wx.getStorageSync('unionid'); //本地分享人的unionid
    console.log('分享店铺信息：', shopInfo);
    console.log('分享妈妈inviter：', inviter);
    return {
      title: '咱+ ' + shopName,
      path: '/pages/home/home?parms=' + shopuid + '/' + inviter + '/0' //店铺id 、分享妈妈id 、分享标识
    }
  },
  //下拉刷新 加载全部商品
  onPullDownRefresh: function() {
    //隐藏加载动画
    this.setData({
      pageNo: 1
    })
    this.loadListByCityNameTask();
    this.getCarouseImgArr();//刷新轮播图

  },
  loadListByCityNameTask: function() {
    this.setData({
      showLoadding: true
    })
    //根据city查询商品列表
    let loadListByCityNameTask = setInterval(() => {
      let cityName = app.data.cityName;
      if (cityName != '') {

        clearInterval(loadListByCityNameTask);

        // 获取商品列表-------------------------------------------------------
        let shopInfo = wx.getStorageSync("shopInfo");
        let [pageNo, shopuid] = [this.data.pageNo, ''];
        shopuid = shopInfo.shopuid || shopuid;

        this.loadHotItemList(shopuid, cityName); //加载热门商品列表
        this.loadItemList(pageNo, shopuid, cityName); //加载普通商品列表（分页）
        this.setData({
          cityArray: app.data.cityArray //城市集合
        })
      }

    }, 100);
  },

  getLocation: function() {
    let cityName = app.data.cityName;

    if (cityName == '成都') {

      this.setCityName(cityName); //设置地理位置

    } else { //获取本地地理位置
      cityName = wx.getStorageSync('cityName') || '';
      console.log('本地cityName=' + cityName);
      //初始化城市信息、本地位置信息为空，获取地理位置
      if (!cityName) {
        wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            let [longitude, latitude] = [res.longitude, res.latitude]; //用户所在经纬度
            this.loadCity(longitude, latitude); //解析地理位置--加载城市

          },
          fail: (res) => { // 拒绝获取地理位置
            this.setCityName(); //设置地理位置
          },
        })
      } else { //本地有城市设置城市
        this.setCityName(cityName); //设置地理位置
      }
    }

  },

  //根据商品id 查商品详情
  selectProductById: function(e) {

    let productId = e.currentTarget.dataset.productid || this.data.productId;
    let isAdImg = e.currentTarget.dataset.type; //点击 首页倒计时广告
    let setTime = isAdImg ? 1000 : 0;
    this.setData({
      productId: productId,
      pageUrl: '/pages/product/product'
    })
    //广告进入商品操作
    let isShowAD = this.data.isShowAD;
    if (isShowAD) { //关闭广告和计时
      this.closeAdAnimation();
    }
    let isAuthorization = app.data.isAuthorization;
    if (isAuthorization === true) {
      setTimeout(() => {
        util.throttle(app.selectProductById, 500, this);
      }, setTime)
    } else {
      util.showToast('请小主先登录咱加~', 1500, 'none', () => {
        wx.hideTabBar();
        this.loginAnimation();
      });
      return
    }

  },
  //跳转到搜索页
  toSearchPage: function(e) {

    this.getFormId(e);
    wx.navigateTo({
      url: '/pages/home/pages/search/search'
    })
  },
  //跳转更多分类
  toCategoryPage: function(e) {
    app.toCategoryPage(e);
  },
  //加载更多
  onReachBottom: function(e) {

    let [pageNo, total] = [this.data.pageNo, this.data.total];
    if (pageNo < total) {
      //加载动画
      this.setData({
        showLoadding: true
      })

      pageNo = pageNo + 1;
      let products = this.data.products; //商品列表
      let [shopInfo, shopuid] = [wx.getStorageSync('shopInfo'), ''];

      if (shopInfo.shopuid) {
        shopuid = shopInfo.shopuid;
      }
      this.loadItemList(pageNo, shopuid, app.data.cityName || '北京');
    } else if (pageNo == total) {
      this.setData({
        showBusiness: true,
      })
    }

  },
  //点击用户登录按钮
  getUserInfo: function(e) {
    console.log('用户登录', e);

    //查看是否允许授权
    let errMsg = e.detail.errMsg;

    if (errMsg == 'getUserInfo:ok') {
      //设置登录按钮状态
      this.setData({
        isLogin: true, //此时用户可点击登录按钮
      })

      app.userLogin(e, this.data.shopuid, this.data.inviter, this.data.shareKey); //携带onload分享的shopuid 数据
      this.userLoginTask(); //检查是否登录成功 + 加载商品列表

    } else { //未授权，打开设置
      //设置登录按钮状态
      this.setData({
        isLogin: false, //此时用户可点击登录按钮
      })

      app.connectionTimeout('请允许获得您的公开信息（头像、昵称）用于登录');
    }
  },


  //------------------关闭/开启购物车动画----------------
  cancelAnimation: function(toCancel) {

    app.cancelAnimation();
    //showSkuList、shareProduct分别为判断显示弹出内容
    this.setData({
      showSkuList: false,
      shareProduct: false,
      animationData: app.data.animationData, //加入购物车动画
    })
    //动画延时播放
    setTimeout(() => {
      this.setData({
        isshow: app.data.isshow,
        showLogin: app.data.showLogin,
        animationData: app.data.animationData, //加入购物车动画
        isLogin: false, //是否点击了登录按钮
      })
    }, 300)
  },
  //商品列表缩略图 图片加载失败出现错误时替换图片路径
  errImg: function(e) {
    let proIndex = e.currentTarget.dataset.proindex; //商品下标
    let [products, hotPorducts] = [
      [],
      []
    ];
    let isSellHot = e.currentTarget.dataset.issellhot; //是否是热销列表

    if (isSellHot == '1') { //热销列表
      hotPorducts = this.data.hotPorducts;
      this.setData({
        hotPorducts: app.errImg(hotPorducts, proIndex) //返回products 更改thumbImgs路径
      })
    } else { //普通商品列表
      products = this.data.products;
      this.setData({
        products: app.errImg(products, proIndex) //返回products 更改thumbImgs路径
      })
    }
  },
  //连接客服中
  connectService: function(e) {
    console.log(e);
    console.log("连接客服中");
  },
  //------------------未开通服务提示----------------------
  unOpen: function() {
    app.unOpen();
  },
  //手动跳过广告
  closeAd: function() {
    clearTimeout(adTime);
    this.closeAdAnimation(); //关闭动画
  },
  //倒计时显示广告
  countAdTime: function() {
    let isShowAD = this.data.isShowAD;

    if (isShowAD) { //如果展示广告
      // wx.hideTabBar();

      let countAdTime = this.data.countAdTime;

      countAdTime = countAdTime - 1;
      if (countAdTime == 0) {
        clearTimeout(adTime);
        this.closeAdAnimation(); //关闭动画
        return;
      } else {
        this.setData({
          countAdTime: countAdTime
        })
        adTime = setTimeout(() => {
          this.countAdTime();
        }, 1000)
      }
    }
  },
  //关闭广告动画
  closeAdAnimation: function() {
    clearTimeout(adTime);
    let animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease',
    })
    this.animation = animation
    animation.scale(0, 0).opacity(0.2).step()

    this.setData({
      closeAdAnimationData: animation.export(),
    })

    setTimeout(() => {
      this.setData({
        countAdTime: app.data.countAdTime, //初始化验证码过期时间
        isShowAD: false,
      })
    }, 400)
  },

  //获取banner轮播
  getCarouseImgArr: function() {

    http.getReq('/weixin/zjCarouseImg/list', {
      cityName: wx.getStorageSync('cityName') || '北京'
    }, (res) => {
      console.log('获取banner轮播', res);
      let interval = res.interval + "000"; //自动切换时间间隔；
      let carouseImgArr = [];
      if (res.carouseImgArr.length > 0) {
        carouseImgArr = res.carouseImgArr; //图片src、商品itemId
      } else {
        carouseImgArr = [];
      }
      this.setData({
        carouseImgArr: carouseImgArr,
        interval: interval || '',
        currentSwiper: 0, //当前播放图片序号
      })
    });

  },
  getFormId: function(e) {
    app.getFormId(e);
  },
  //变更展示一行展示多少商品数
  changeLineNum: function() {
    this.setData({
      showLine1: !this.data.showLine1
    })
  },
  changeImgHeight: function() {
    wx.createSelectorQuery().selectAll('.proSection1').boundingClientRect((rects) => {
      let imgHeight = ''
      rects.forEach(function(rect) {
        imgHeight = rect.width; // 节点的宽度
      })
      this.setData({
        imgHeight: imgHeight
      })
    }).exec()
  },
  //加载热门商品列表 --参数shopuid
  loadHotItemList: function(shopuid, cityName) {

    console.log("请求首页商品列表shopuid:" + shopuid);

    http.getReq('/weixin/item/hotItemList', {
      shopuid: shopuid, //用于根据店铺id查找该店铺上架的商品
      cityName: cityName
    }, (res) => {
      // console.log('hotPorducts列表:', res);
      let hotPorducts = res.data;
      //设置热销商品数据
      this.setData({
        hotPorducts: hotPorducts,
        showLoadding: false //隐藏加载动画
      })
    });

  },
  //分页加载全部商品列表--参数 pageNo, shopuid
  loadItemList: function(pageNo, shopuid, cityName) {

    let localPageNo = this.data.pageNo;
    if (pageNo != localPageNo || pageNo == 1) {
      // console.log('app.data.pageSize', app.data.pageSize);
      let [products, setProList, pageSize] = [[], [], app.data.pageSize];//加载分页的商品列表（用于局部刷新）
      //获取商品列表-------------------------------------------------------
      http.getReq('/weixin/item/itemList', {
        pageNo: pageNo || 1,
        pageSize: pageSize,
        shopuid: shopuid, //用于根据店铺id查找该店铺上架的商品
        cityName: cityName, //城市名称
      }, (res) => {
        // console.log('loadItemList', res.data,pageNo);
        let newList = res.data;//返回的商品数据
        
        if (pageNo > 1) {
          products = this.data.products;//原商品列表
          
          for (let item of newList){
            setProList[`products[${products.length}]`] = item;
            products.length++;
          }
          // console.log('setProList', setProList);
          this.setData({
            ...setProList
          })

        }else{//第一次加载商品
          products.push(...newList);
          this.setData({
            products: products
          })
        }

        this.setData({
          pageNo: pageNo || 1,
          total: res.total,
          showLoadding: false //隐藏加载动画
        })
        // console.log('products',products);
        //改变图片高度
        wx.stopPullDownRefresh();

        //获取商户和用户距离
        this.calculateDistance();

      });
    }

  },
  //你想解析用户坐标获取城市
  loadCity: function(longitude, latitude) {

    console.log('解析地理位置信息');

    // 调用接口
    demo.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: (res) => {

        let cityName = res.result.address_component.city;

        //开放两个城市
        cityName = (cityName == '天津市') ? '天津' : '北京';
        //同步数据，保存到本地
        this.setCityName(cityName);
      },
      fail: (res) => {
        console.log('解析地理位置失败');
        this.setCityName();
      }

    });
  },
  //设置城市
  setCityName: function(cityName) {
    console.log('setCityName==', cityName);

    app.setCityName(cityName);

    this.setData({
      cityName: app.data.cityName
    })
  },

  //改变选择城市
  onCityChange: function(e) {

    let [cityArray, index] = [this.data.cityArray, e.detail.value];
    let newCityName = cityArray[index];
    if (newCityName == app.data.cityName) { //选择城市相同
      return
    }

    app.onCityChange(e);

    let cityName = app.data.cityName;
    this.setData({
      cityName: cityName,
      areaIcon: !this.data.areaIcon,
      products: [],
      hotPorducts: []
    })

    this.setCityName(cityName); //更改本地city名称

    //根据城市查询商品
    let shopInfo = wx.getStorageSync("shopInfo");
    let [pageNo, shopuid] = [1, ''];
    shopuid = shopInfo.shopuid || shopuid;


    this.loadHotItemList(shopuid, cityName); //加载热门商品列表
    this.loadItemList(pageNo, shopuid, cityName); //加载普通商品列表（分页）
    this.getCarouseImgArr(); //根据城市切换首页banner
  },
  onCityCancel: function() {
    this.setData({
      areaIcon: !this.data.areaIcon
    })
  },
  //更换地域选择图标
  changeAreaIcon: function() {
    this.setData({
      areaIcon: !this.data.areaIcon
    })
  },
  onHide: function() {
    this.setData({
      shareKey: '',
      pinUser: ''
    })
  },
  //通知滚动事件
  // noticeScroll:function(e){
  //   console.log('通知滚动回调');
  //   console.log(e);

  // },
  //上新滚动条滚动：
  // noticeRoll:function(){
  //   let isBottom = this.data.isBottom;//是否触底
  //   let noticeScrollTop = this.data.noticeScrollTop;//距离顶部距离
  //   var loop = setInterval(()=>{
  //     if (!isBottom){
  //       noticeScrollTop = noticeScrollTop + 5
  //       this.setData({
  //         noticeScrollTop: noticeScrollTop++
  //       })
  //     }
  //   },500)
  // },
  // noticLower:function(e){
  //   console.log('已经触底了');
  //   console.log(e);

  // },
  /**
   * 计算商户和用户距离
   */
  calculateDistance: function() {
    demo.calculateDistance({
      to: [{
        latitude: this.data.shopLatitude,
        longitude: this.data.shopLongitude,
      }],
      success: (res) => {
        console.log('计算商户和用户距离', res);
        let distance = '';
        let meter = res.result.elements[0].distance;
        if (meter < 500) {
          distance = '< 500m';
        } else if (meter >= 500 && meter < 1000) {
          distance = meter + 'm';
        } else {
          distance = (meter / 1000).toFixed(1) + 'km';
          console.log('distance', distance);
        }
      },
      fail: (res) => {
        console.log('计算距离失败');
      },

    });
  },
  /**
   * 领取优惠券
   */
  receiveCoupon: function() {

    http.getReq('/weixin/couponInfo/save', {
      rdSession: wx.getStorageSync('rd_session')
    }, (res) => {
      wx.showTabBar();
      console.log('领取优惠券receiveCoupon', res);
      if (res.ret) {
        this.setData({
          isshow: false,
          hasShopCoupon: '',
        })
        // app.checkShopCoupon(this.data.shareKey);
        util.showToast('领取成功', 1000, 'success', () => {});
      }
    });

  },
  /*
  关闭优惠券
   */
  cancelCoupon: function() {
    wx.showTabBar();
    this.setData({
      isshow: false,
      hasShopCoupon: ''
    })
  },
  //查看有是否有分享店铺的优惠券
  checkShopCouponTask: function() {
    let checkShopCouponTask = setInterval(() => {
      let hasShopCoupon = app.data.hasShopCoupon;
      if (hasShopCoupon !== '') {
        console.log('hasShopCoupon' + hasShopCoupon);
        clearInterval(checkShopCouponTask);
        if (hasShopCoupon == '1') {
          wx.hideTabBar();
          this.showCouponTask(); //展示领取优惠券窗口
        } else {
          wx.showTabBar();
        }
        this.setData({
          hasShopCoupon: app.data.hasShopCoupon
        })
      }
    }, 500)
  },
  // 加载关注公众号组件成功
  loadAccount: function(e) {
    console.log('loadAccount', e);
  },
  // 查看营业执照
  toShowBusiness: function() {
    wx.navigateTo({
      url: '/pages/home/pages/business/business',

    })
  },

  /**
   * 引导添加‘我的小程序’蒙层
   */
  handleGuideMask:function(){
    console.log('handleGuideMask');
    this.setData({
      showGuideMask:true,
      isshow:true
    })
  },
  cancelGuideMask:function(){
    this.setData({
      showGuideMask: false,
      isshow: false,
      showCollectionTip:false
    })
  }
})